package com.explorex.infra.puma.gateway.netty.ws.message.handler;

import com.explorex.infra.puma.gateway.netty.common.AuthStatusEnum;
import com.explorex.infra.puma.gateway.netty.ws.WebSocketSession;
import com.explorex.infra.puma.gateway.netty.ws.enums.MessageTypeEnum;
import com.explorex.infra.puma.gateway.netty.ws.message.Message;
import com.explorex.infra.puma.gateway.netty.ws.message.MessageBody;
import com.explorex.infra.puma.gateway.netty.ws.message.MessageHeader;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;

/**
 * @author: JacceYang
 * @createTime: 2022/07/19 11:28 上午
 * @description: 关闭通道消息处理器
 */
@Slf4j
public class CloseChannelMessageProcessor extends AbstractBaseProcessor {

    private static final CloseChannelMessage Instance = new CloseChannelMessage();

    @Override
    public short getMessageType() {
        return MessageTypeEnum.CLOSE_SOCKET.getType();
    }

    @Override
    public Message process(WebSocketSession session, Message messageFrame) {
        if (session.getAuth() != AuthStatusEnum.AUTHED) {
            // only log this message ,and close the socket
            log.warn("unAuth request ");
        }
        return buildAck(messageFrame);
    }

    private Message buildAck(Message messageFrame) {
        MessageHeader header = new MessageHeader(MessageTypeEnum.CLOSE_SOCKET_ACK.getType());
        Message message = new Message();
        message.setHeader(header);
        header.trackHeader(messageFrame.getHeader());
        return message;
    }

    @Override
    public MessageBody doParseBody(int contentType, String msgBody) throws Exception {
        return Instance;
    }

    @Data
    public static class CloseChannelMessage implements MessageBody, Serializable {
        private String reason;
    }
}
